package likou.duoxianc;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2021/10/10 14:12
 */
public class _1117 {

    public _1117() {

    }

    int O = 1;
    int H = 2;
    Object lock1 = new Object();
    Object lock2 = new Object();

    public void hydrogen(Runnable releaseHydrogen) {
        try {
            synchronized (lock1) {
                if (O == 0) {
                    if (H == 0) {
                        O = 1;
                        H = 2;
                        lock2.notifyAll();
                    } else {
                        lock1.wait();
                    }
                }
                O--;
                releaseHydrogen.run();
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void oxygen(Runnable releaseOxygen) {
        try {
            synchronized (lock2) {
                if (H == 0) {
                    if (O == 0) {
                        O = 1;
                        H = 2;
                        lock1.notifyAll();
                    } else {
                        lock2.wait();
                    }
                }
                H--;
                releaseOxygen.run();
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
